package cn.stu.action;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import cn.stu.service.UserService;
import cn.stu.utils.BaseServlet;
import cn.stu.vo.User;

public class UserServlet extends BaseServlet{
	

	private static final HttpServletResponse response = null;

	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @return
	 */
	public String login(HttpServletRequest request, HttpServletResponse response){
		//接收数据
		Map<String, String[]> map = request.getParameterMap();
		User user = new User();
		//封装数据
		try {
			BeanUtils.populate(user, map);
			
			//调用Service层处理数据
			UserService userService = new UserService();
			User existUser = userService.login(user);
			
			if (existUser == null) {
				//用户登录失败
				request.setAttribute("msg", "用户密码错误！");
				return "/index.jsp";
			} else {
				//用户登陆成功
				//销毁同一个浏览器中，上一个用户的session,这是为了防止上一个用户的一些存储在session中的信息，被下一个用户所遗留
				request.getSession().invalidate();
				//不同浏览器登录同一个账号时，遇见的BUG，
				Map<User, HttpSession> userMap =  (Map<User, HttpSession>) getServletContext().getAttribute("userMap");
				//判断集合中是否有这个用户
				if (userMap.containsKey(existUser)) {
					HttpSession session = userMap.get(existUser);
					//销毁该用户的session
					session.invalidate();
				}
				
				
				//使用监听器，HttpSessionBandingListener;作用在一个javaBean上，用来监听一个java对象在session中的状态的改变	
				request.getSession().setAttribute("existUser", existUser);
				ServletContext application = getServletContext();
				
				String sourceMessage = "";
				if (null != application.getAttribute("message")) {
					sourceMessage = application.getAttribute("message").toString();
				}
				
				sourceMessage += "系统公告：<font color='gray'>"
						+ existUser.getUsername() + "走进了聊天室！</font><br>";
				application.setAttribute("message", sourceMessage);

				response.sendRedirect(request.getContextPath() + "/main.jsp");
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 踢人下线
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public String kick(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//接收参数
		int id = Integer.parseInt(request.getParameter("id"));
		//踢人将用户对应的session从userMap中移除
		Map<User, HttpSession> userMap = (Map<User, HttpSession>) getServletContext().getAttribute("userMap");
		User user = new User();
		user.setId(id);
		HttpSession session = userMap.get(user);
		session.invalidate();
		//重定向到main.jsp页面
		response.sendRedirect(request.getContextPath()+"/main.jsp");
		return null;
	}
	/**
	 * 获取聊天信息
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public String getMessage(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String message = (String) getServletContext().getAttribute("message");
		if(message != null){
			response.getWriter().println(message);
		}
		
		return null;
	}
	
	/**
	 * 发送聊天内容
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public String sendMessage(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//1.接受数据
		System.out.println("发送数据中...");
		String from = request.getParameter("from");  //发言人
		String face = request.getParameter("face");  //表情
		String to = request.getParameter("to");    //接受者
		String color = request.getParameter("color"); //字体颜色
		String content = request.getParameter("content"); //发言内容
		//发言时间 正常情况下使用SimpleDateFormat
		String sendTime = new Date().toLocaleString();
		
		//获取ServletContext对象
		ServletContext application = getServletContext();
		//从ServletContext中获取消息
		String sourceMessage = (String) application.getAttribute("message");
		
		// 拼接发言的内容:xx 对 yy 说 xxx
		sourceMessage += "<font color='blue'><strong>" + from
				+ "</strong></font><font color='#CC0000'>" + face
				+ "</font>对<font color='green'>[" + to + "]</font>说："
				+ "<font color='" + color + "'>" + content + "</font>（"
				+ sendTime + "）<br>";

		//将消息存入到application中
		application.setAttribute("message", sourceMessage);
		return getMessage(request, response);
	}							
	/**
	 * 退出聊天室,销毁Session对象
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public String exit(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//销毁session对象
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath()+"/index.jsp");
		return null;
	}
	/**
	 * 时刻监控用户是否在线
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public String check(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//从session中获得用户信息
		 User existUser = (User) request.getSession().getAttribute("existUser");
		//判断session是否过期
		 if (existUser == null) {
			 //登录信息已过期
			 response.getWriter().println("2");
		} else {
			//登录信息未过期
			response.getWriter().println("1");
		}
		return null;
	}
	
}
